<template>
  <section class="f-shopLevel">
    <div class="w-card my-content-box">
      <div class="title-box">
        <span class="title-text">店铺等级列表</span>
        <div>
          <el-button type="primary" plain @click="openDialog(1)">+ 新增店铺等级</el-button>
        </div>
      </div>

      <div class="my-search-box">
        <div>
          <span>店铺名称：</span>
          <el-input v-model="searchForm.shopName" clearable placeholder="请输入店铺名称" />
        </div>
        <div>
          <span>等级类别：</span>
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="采购等级" value="2" />
            <el-option label="设置等级" value="3" />
          </el-select>
        </div>
        <div class="datebox">
          <span>创建时间：</span>
          <el-date-picker v-model="searchForm.date" type="monthrange" value-format="x" start-placeholder="开始月份"
            end-placeholder="结束月份" @change="selectDate" />
        </div>
        <div class="f-ml-20">
          <el-button @click="searchHandle" type="primary">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
      </div>

      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="selectionChange">
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="shopId" label="店铺ID" align="center">
            <template v-slot="scope">
              {{ scope.row.shopId || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="shopName" label="店铺名称" align="center">
            <template v-slot="scope">
              {{ scope.row.shopName || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="shopPhone" label="店铺号码" align="center">
            <template v-slot="scope">
              {{ scope.row.shopPhone || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="vipLevel" label="店铺等级" align="center">
            <template v-slot="scope">
              {{ scope.row.vipLevel || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="有效期" align="center">
            <template v-slot="scope">
              {{ scope.row.startMonth || '--' }} 至 {{ scope.row.endMonth || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="等级类别" align="center">
            <template v-slot="scope">
              {{ scope.row.type == 2? '采购等级': scope.row.type == 3? '设置等级': '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="delFlag" label="状态" align="center">
            <template v-slot="scope">
              {{ scope.row.delFlag == 1? '正常': scope.row.delFlag == 0? '已删除': '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" align="center">
            <template v-slot="scope">
              {{ scope.row.remarks || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="创建信息" align="center">
            <template v-slot="scope">
              <p>{{ scope.row.createUser || '--' }}</p>
              <p>{{ getDateTime(scope.row.createTime)[6] }}</p>
            </template>
          </el-table-column>
          <el-table-column label="更新信息" align="center">
            <template v-slot="scope">
              <p>{{ scope.row.modifyUser || '--' }}</p>
              <p>{{ getDateTime(scope.row.modifyTime)[6] }}</p>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template v-slot="scope">
              <div class="table-handle-box">
                <el-link style="font-size:14px;" type="danger" @click="settingHandle('delete',scope.row)">
                  删除
                </el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <!-- <div class="footer_btn_box">
              <el-button :disabled="chooseList.length == 0" @click="settingHandle('delete')" type="danger" plain>删除</el-button>
            </div> -->
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>

      <!-- 确认密码 -->
      <ConfirmPass ref="confirmPasswordRef" @verification="confirmSuccess" />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogForm.title" width="600" :close-on-click-modal="false">
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules">
        <el-form-item prop="shopId" label="选择店铺">
          <el-select v-model="dialogForm.shopId" filterable clearable>
            <el-option v-for="(item,index) in shopList" :key="index" :label="item.shopName" :value="item.shopId" />
          </el-select>
        </el-form-item>
        <el-form-item prop="vipLevel" label="店铺等级">
          <el-input v-model="dialogForm.vipLevel" type="number" clearable placeholder="请输入店铺等级" />
        </el-form-item>
        <el-form-item prop="startMonth" label="开始月份">
          <el-date-picker v-model="dialogForm.startMonth" type="month" value-format="YYYY-MM" placeholder="请选择月份"
            style="width: 100% !important" :disabled-date="disabledDate" />
        </el-form-item>
        <el-form-item prop="endMonth" label="结束月份">
          <el-date-picker v-model="dialogForm.endMonth" type="month" value-format="YYYY-MM" placeholder="请选择月份"
            style="width: 100% !important" :disabled-date="disabledDateEnd" :disabled="!dialogForm.startMonth" />
        </el-form-item>
        <el-form-item prop="remarks" label="备注">
          <el-input v-model="dialogForm.remarks" :rows="3" type="textarea" placeholder="请输入备注..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel()">取消</el-button>
          <el-button type="primary" @click="dialogSave()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </section>
</template>
  
  <script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad, getUnixTime } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import ConfirmPass from '@/components/confirmPass.vue'
import api from './api'

export default {
  components: { ConfirmPass },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const confirmPasswordRef = ref(null)
    const dialogFormRef = ref(null)

    const state = reactive({
      searchForm: {
        "createTimeMax": "",
        "createTimeMin": "",
        "orderBy": "id desc",
        "shopName": "",
      },

      tableHeight: 0,
      tableData: [{}],
      page: 1,
      size: 10,
      total: 0,

      chooseList: [],
      selectData: {},

      dialogVisible: false,
      dialogForm: {},
      dialogRules: {
        shopId: [
          { required: true, message: "请选择店铺", trigger: "change" },
        ],
        startMonth: [
          { required: true, message: "请选择开始月份", trigger: "change" },
        ],
        endMonth: [
          { required: true, message: "请选择结束月份", trigger: "change" },
        ],
        vipLevel: [
          { required: true, message: "请输入店铺等级", trigger: "blur" },
        ],
        remarks: [
          { required: true, message: "请输入备注", trigger: "blur" },
        ],
      },

      shopList: [],
      nextYear: ''
    })

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {
        "createTimeMax": "",
        "createTimeMin": "",
        "orderBy": "id desc",
        "shopName": "",
      }
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
      }
      api.shoplevelList(obj).then(res => {
        state.tableData = res.data.list
        state.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function settingHandle(type, data) {
      let title = ""
      let msg = ''
      if (type == 'delete') {
        title = '删除提示'
        msg = `您确定要将所选的店铺等级吗？`
      }
      // if (state.chooseList.length == 0) {
      //   return
      // }
      state.selectData = data
      confirmPasswordRef.value.dialogShow(title, msg, type)
    }

    const confirmSuccess = (type) => {
      if (type == 'delete') {
        let json = {
          uniqueId: state.selectData.id
        }
        api.shoplevelDelete(json).then(res => {
          successDeal('操作成功！')
          getTableData()
        })
      }
    }

    function selectionChange(list) {
      state.chooseList = list
    }

    const openDialog = (type, data) => {
      if (type == 1) {
        state.dialogForm.title = '新增店铺等级'
      }
      state.dialogVisible = true
    }

    const dialogCancel = () => {
      state.dialogVisible = false
      state.dialogForm = {}
      dialogFormRef.value.resetFields()
    }

    const dialogSave = () => {
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          if (state.dialogForm.title == '新增店铺等级') {
            let json = JSON.parse(JSON.stringify(state.dialogForm))
            api.shoplevelAdd(json).then(res => {
              successDeal('操作成功！')
              getTableData()
              dialogCancel()
            })
          }
        }
      })
    }

    const selectDate = (e) => {
      state.searchForm.createTimeMin = e[0]
      state.searchForm.createTimeMax = e[1]
    }

    const getShopChooseList = () => {
      api.shopChooseList().then(res => {
        state.shopList = res.data.list
      })
    }

    const disabledDate = (time) => {
      return (time.getTime() < Date.now() - 8.64e7) || (time.getTime() > state.nextYear)
    }

    const disabledDateEnd = (time) => {
      if (state.dialogForm.startMonth) {
        return time.getTime() < getUnixTime(state.dialogForm.startMonth) + 24 * 60 * 60 * 1000 * 31
      }
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 290
      getTableData()
      getShopChooseList()


      let nextYear = new Date().getFullYear() + 1
      state.nextYear = getUnixTime(String(nextYear)) - 9 * 60 * 60 * 1000
      console.log(state.nextYear)
    })

    return {
      ...toRefs(state),
      dialogFormRef,
      confirmPasswordRef,
      getDateTime,
      searchHandle,
      resetHandle,
      handleCurrentChange,
      handleSizeChange,
      settingHandle,
      confirmSuccess,
      selectionChange,
      dialogCancel,
      dialogSave,
      openDialog,
      selectDate,
      disabledDate,
      disabledDateEnd,
    }
  }
}
  </script>
  
  <style lang="scss" scoped>
.f-shopLevel {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    > .title-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 300px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 90px;
          text-align: right;
        }
      }

      .datebox {
        width: 500px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
}
</style>